import { createRouter, createWebHistory, type RouteRecordRaw ,createWebHashHistory} from 'vue-router'
import { defaultRoutes,dynamicRoutes,notFoundAndNoPower } from './routes'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Local, Session, showMsg, useTitle } from '@/utils';
import { TOKEN_KEY } from '@/const';
import { initBackEndControlRoutes } from './background';
import { useKeepAliveNames } from '@/stores/keepAliveNames';
import { useRoutesList } from '@/stores/routesList';
import { storeToRefs } from 'pinia';
import { clearAccessAfterReload } from '@/api/request';


NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 更改启动时使用的最小百分比
  parent: 'body', //指定进度条的父容器
})
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    ...defaultRoutes,
    ...notFoundAndNoPower,
    // ...dynamicRoutes
  ],
})

router.beforeEach(async (to, from, next) => {
	const token = Local.get(TOKEN_KEY)
	if(to.path === '/login' && !token){
		next()
		return
	}
	if(to.meta.isPublic && !token){
		// 处理公共路由情况
		next()
	}else {
		if(!token){
			// 如果没有token的情况下直接跳转登录页
			Session.clear()
			Local.clear()
			next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`);
		}else if(token && to.path === '/login'){
			// 如果存在token但是跳转登录页则重定向首页
			next('/dashboard/home')
		}else {
			// 判断当前pinia中是否获取过菜单路由数据，有就直接使用，没有就重新请求
			const storesRoutesList = useRoutesList()
			const {state}= storeToRefs(storesRoutesList)
			if(state.value.routesList.length ===0){;
				await initBackEndControlRoutes()
				next({ path: to.path, query: to.query })
			}else {
				next()
			}
		}
	}
})

router.afterEach((to,from)=>{
})

/**
 * 扁平化数组处理路由表(一维数组)
 * @param arr dynamicRoutes
 * @returns 
 */
export const formatFlatteningRoutes = (arr: any) => {
	if (arr.length <= 0) return false;
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].children) {
			arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
		}
	}
	return arr;
}

/**
 * 一维数组处理成多级嵌套数组（只保留二级：也就是二级以上全部处理成只有二级，keep-alive 支持二级缓存）
 * 全部处理为一维数组
 * @param arr 
 */
export const formatTwoStageRoutes = (arr: any) => {
	if (arr.length <= 0) return false;
	const newArr: any = [];
	const cacheList: Array<string> = [];
	arr.forEach((v: any) => {
		if (v.path == null || v.path == undefined) return;

		if (v.path === '/') {
			newArr.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: [] });
		} else {
			// 判断是否是动态路由（xx/:id/:name），用于 tagsView 等中使用
			// 修复：https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
			if (v.path.indexOf('/:') > -1) {
				v.meta['isDynamic'] = true;
				v.meta['isDynamicPath'] = v.path;
			}
			if(!Array.isArray(newArr[0].children)){
				newArr[0].children = []
			}
			newArr[0].children.push({ ...v });
			// 存 name 值，keep-alive 中 include 使用，实现路由的缓存
			// 路径：/@/layout/routerView/parent.vue
			if (newArr[0].meta && newArr[0].meta.isKeepAlive && v?.meta.isKeepAlive) {
				cacheList.push(v.name);
			}
		}
	});
	const keepAliveNames =useKeepAliveNames()
	keepAliveNames.setCacheKeepAlive(cacheList)
	return newArr;
}

export default router
